﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.input
{
    public partial class LL_RK : Form
    {
        public LL_RK()
        {
            InitializeComponent();
        }
        bool flag = false;
        bool result = false;
        string Location_SN = string.Empty;
        string Storage_SN = string.Empty;
        string Area_SN = string.Empty;

        private bool ValidateInput()
        {
            if (string.IsNullOrEmpty(txt_reelid.Text.Trim()))
            {
                SetLabelMsg(false, "Reelid不能为空", "reelid");
                return false;
            }
            string sql = string.Format(@"SELECT *  FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber='{0}'", txt_reelid.Text.Trim());
            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt.Rows.Count > 0)
            {
                SetLabelMsg(false, "Reelid请勿重复入库", "reelid");
                return false;
            }
            Location_SN = string.Empty;
            Storage_SN = string.Empty;
            Area_SN = string.Empty;
            string strsql_check_qd = string.Format(@"
IF NOT EXISTS ( SELECT  *
                FROM    T_Bllb_StorageDocDetail_tbsdd
                WHERE   SerialNumber = '{0}' )
    BEGIN
        SELECT  '0' ,
                'Reelid未清点'
        RETURN
    END
ELSE
    BEGIN
        DECLARE @result NVARCHAR(50) ,
            @materialCode NVARCHAR(50) ,
            @qty NVARCHAR(50)
        DECLARE @DateCode NVARCHAR(50) ,
            @Lot_No NVARCHAR(50) ,
            @Is_SendCheck NVARCHAR(50),
			@MPN NVARCHAR(50),
			@Version NVARCHAR(50)
        SELECT  @Is_SendCheck = a.IsSendCheck ,
                @qty = b.QTY ,
                @DateCode = b.DateCode ,
                @Lot_No = b.Lot_No ,
                @materialCode = b.MaterialCode,
				@MPN=b.MPN,
			    @Version=b.[Version]
        FROM    dbo.MdcdatMaterial AS a
                LEFT JOIN T_Bllb_StorageDocDetail_tbsdd AS b ON a.MaterialCode = b.MaterialCode
        WHERE   b.SerialNumber = '{0}'  ORDER BY B.CREATE_TIME DESC
        IF ( @Is_SendCheck = '否' )
            BEGIN
				--检验OK
                SELECT  '1' ,
                        'OK' ,
                        @materialCode AS 'MaterialCode' ,
                        @DateCode AS 'DateCode' ,
                        @Lot_No AS 'Lot_No' ,
                        @qty AS 'Qty',
						@MPN AS 'MPN',
					    @Version AS 'Version'
                RETURN
            END        
        SELECT TOP 1
                @result = a.RESULT
        FROM    [dbo].[T_Bllb_IQCDoc_tbid] AS a
                LEFT JOIN dbo.T_Bllb_IQCProduct_tbip AS b ON b.IQC_NO = a.IQC_NO
        WHERE   b.SERIAL_NUMBER = '{0}'
        ORDER BY a.CREATE_TIME DESC
        IF ( @result = ''
             OR @result IS NULL
           )
            BEGIN
                SELECT  '0' ,
                        'reeild检验状态无法入库'
                RETURN
            END
        IF ( @result = '1' )
            BEGIN
				--检验OK
                SELECT  '1' ,
                        '检验OK' ,
                        @materialCode AS 'MaterialCode' ,
                        @DateCode AS 'DateCode' ,
                        @Lot_No AS 'Lot_No' ,
                        @qty AS 'Qty',
						@MPN AS 'MPN',
						@Version AS 'Version'
                RETURN
            END
        ELSE
            IF ( @result = '2' )
                BEGIN
                    SELECT  '2' ,
                            '检验NG' ,
                            @materialCode AS 'MaterialCode' ,
                            @DateCode AS 'DateCode' ,
                            @Lot_No AS 'Lot_No' ,
                            @qty AS 'Qty',
							@MPN AS 'MPN',
						    @Version AS 'Version'
                    RETURN
                END		     
    END			      ", txt_reelid.Text.Trim());
            DataTable dtCheck = Utils.NMS.QueryDataTable(Utils.uContext, strsql_check_qd, new CIT.WMS.MESWcf.CmdParameter[0]);

            if (dtCheck.Rows[0][0].ToString() == "0")
            {
                SetLabelMsg(false, dtCheck.Rows[0][1].ToString(), "reelid");
                return false;
            }
            string MaterialCode = SqlInput.ChangeNullToString(dtCheck.Rows[0]["MaterialCode"]);//料号
            int Qty = SqlInput.ChangeNullToInt(dtCheck.Rows[0]["Qty"], 0);//数量
            string DateCode = SqlInput.ChangeNullToString(dtCheck.Rows[0]["DateCode"]);//DateCode
            string Lot_No = SqlInput.ChangeNullToString(dtCheck.Rows[0]["Lot_No"]);//批次
            string MPN = SqlInput.ChangeNullToString(dtCheck.Rows[0]["MPN"]);//MPN
            string Version = SqlInput.ChangeNullToString(dtCheck.Rows[0]["Version"]);//Version
            if (dtCheck.Rows[0][0].ToString() == "1")
            {
                StringBuilder sql_ok_location = new StringBuilder(@"
SELECT  a.Storage_SN ,
        a.Storage_Name ,
        b.Area_SN ,
        b.Area_Name ,
        c.Location_SN ,
        c.Location_Name
FROM    dbo.T_Bllb_Storage_tbs AS a
        LEFT JOIN dbo.T_Bllb_StorageArea_tbsa AS b ON a.Storage_SN = b.Storage_SN
        LEFT  JOIN dbo.T_Bllb_StorageLocation_tbsl AS c ON b.Area_SN = c.Area_SN
WHERE   a.Storage_SN='SAA001'");

                if (!string.IsNullOrEmpty(txtLocation.Text.Trim()))
                {
                    string location_where = string.Format(" AND c.Location_SN = '{0}'", txtLocation.Text.Trim());
                    sql_ok_location.Append(location_where);
                }
                DataTable dt_okLocation = Utils.NMS.QueryDataTable(Utils.uContext, sql_ok_location.ToString(), new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_okLocation.Rows.Count > 0)
                {
                    Storage_SN = SqlInput.ChangeNullToString(dt_okLocation.Rows[0]["Storage_SN"]);
                    if (!string.IsNullOrEmpty(txtLocation.Text.Trim()))
                    {
                        Location_SN = SqlInput.ChangeNullToString(dt_okLocation.Rows[0]["Location_SN"]);
                        Area_SN = SqlInput.ChangeNullToString(dt_okLocation.Rows[0]["Area_SN"]);
                    }

                    string sql_save_ok_stock = string.Format(@"
		INSERT dbo.T_Bllb_StockInfo_tbsi	
		        ( Storage_SN ,
		          Area_SN ,
		          Location_SN ,
		          MaterialCode ,
		          QTY ,
		          Lock_Flag ,
		          Enable ,
		          In_Time ,
		          SerialNumber ,
		          Status_Flag ,
		          DateCode ,
		          Finally_Time ,
		          Lot_No ,
		          QC_Result,
                  MPN,
                  Version
		        )
		VALUES  ( '{0}' , -- Storage_SN - nvarchar(50)
		          '{1}' , -- Area_SN - nvarchar(50)
		          '{2}' , -- Location_SN - nvarchar(50)
		          '{3}' , -- MaterialCode - nvarchar(50)
		          '{4}' , -- QTY - int
		          '0' , -- Lock_Flag - varchar(10)
		          'Y' , -- Enable - varchar(10)
		          GETDATE() , -- In_Time - datetime
		          '{5}' , -- SerialNumber - nvarchar(200)
		          '1' , -- Status_Flag - varchar(10)
		          '{6}' , -- DateCode - nvarchar(50)
		          '{6}' , -- Finally_Time - datetime
		          '{7}' , -- Lot_No - nvarchar(50)
		          '1' , -- QC_Result - nvarchar(50)
                  '{8}',
                  '{9}'
		        )", Storage_SN, Area_SN, Location_SN, MaterialCode, Qty, txt_reelid.Text.Trim(), DateCode, Lot_No, MPN, Version);
                    Utils.NMS.Exectransql(Utils.uContext, sql_save_ok_stock, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    string sql_expiredate = string.Format(@"
--保质期
DECLARE @shelfTime NVARCHAR(100)
--条码
DECLARE @finlly_time NVARCHAR(100)
SELECT  @shelfTime = b.ShelfLifeTime ,
        @finlly_time = a.Finally_Time
FROM    dbo.T_Bllb_StockInfo_tbsi AS a
        LEFT JOIN dbo.MdcdatMaterial AS b ON a.MaterialCode = b.MaterialCode
WHERE   a.SerialNumber = '{0}'
IF ( @shelfTime IS NOT NULL
     AND @shelfTime <> '0'
     AND @shelfTime <> ''
   )
    BEGIN
        UPDATE  T_Bllb_StockInfo_tbsi
        SET     Finally_Time = DATEADD(MONTH, CAST(@shelfTime AS INT),
                                       CAST(@finlly_time AS DATETIME))
        WHERE   SerialNumber = '{0}'
    END
", txt_reelid.Text.Trim());
                    Utils.NMS.Exectransql(Utils.uContext, sql_expiredate, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    WriteLog(txt_reelid.Text.Trim(), "来料入库", MaterialCode, Qty);
                    SetLabelMsg(true, "入库成功", "ok");
                    return true;
                }
                else
                {
                    SetLabelMsg(false, "未建立原料仓或库位错误", "location");
                    return false;
                }
            }
            //else if (dtCheck.Rows[0][0].ToString() == "2")
            else
            {
                if (string.IsNullOrEmpty(txtLocation.Text.Trim()))
                {
                    SetLabelMsg(false, "Reeild检验NG,库位必填", "location");
                    return false;
                }
                else
                {
                    string sql_ng_location = string.Format(@"
SELECT  a.Storage_SN ,
        a.Storage_Name ,
        b.Area_SN ,
        b.Area_Name ,
        c.Location_SN ,
        c.Location_Name
FROM    dbo.T_Bllb_Storage_tbs AS a
        LEFT JOIN dbo.T_Bllb_StorageArea_tbsa AS b ON a.Storage_SN = b.Storage_SN
        LEFT  JOIN dbo.T_Bllb_StorageLocation_tbsl AS c ON b.Area_SN = c.Area_SN
WHERE   c.Location_SN = '{0}' AND a.Storage_Type='2'  ", txtLocation.Text.Trim());
                    DataTable dt_nglocation = Utils.NMS.QueryDataTable(Utils.uContext, sql_ng_location, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_nglocation.Rows.Count > 0)
                    {
                        Location_SN = SqlInput.ChangeNullToString(dt_nglocation.Rows[0]["Location_SN"]);
                        Storage_SN = SqlInput.ChangeNullToString(dt_nglocation.Rows[0]["Storage_SN"]);
                        Area_SN = SqlInput.ChangeNullToString(dt_nglocation.Rows[0]["Area_SN"]);
                        string sql_save_ng_stock = string.Format(@"
		INSERT dbo.T_Bllb_StockInfo_tbsi	
		        ( Storage_SN ,
		          Area_SN ,
		          Location_SN ,
		          MaterialCode ,
		          QTY ,
		          Lock_Flag ,
		          Enable ,
		          In_Time ,
		          SerialNumber ,
		          Status_Flag ,
		          DateCode ,
		          Finally_Time ,
		          Lot_No ,
		          QC_Result,
                  MPN,
                  Version 
		        )
		VALUES  ( '{0}' , -- Storage_SN - nvarchar(50)
		          '{1}' , -- Area_SN - nvarchar(50)
		          '{2}' , -- Location_SN - nvarchar(50)
		          '{3}' , -- MaterialCode - nvarchar(50)
		          '{4}' , -- QTY - int
		          '0' , -- Lock_Flag - varchar(10)
		          'Y' , -- Enable - varchar(10)
		          GETDATE() , -- In_Time - datetime
		          '{5}' , -- SerialNumber - nvarchar(200)
		          '1' , -- Status_Flag - varchar(10)
		          '{6}' , -- DateCode - nvarchar(50)
		          '{6}' , -- Finally_Time - datetime
		          '{7}' , -- Lot_No - nvarchar(50)
		          '2',  -- QC_Result - nvarchar(50)
                  '{8}',
                  '{9}'
		        )", Storage_SN, Area_SN, Location_SN, MaterialCode, Qty, txt_reelid.Text.Trim(), DateCode, Lot_No, MPN, Version);
                        Utils.NMS.Exectransql(Utils.uContext, sql_save_ng_stock, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                        WriteLog(txt_reelid.Text.Trim(), "检验NG-来料入库", MaterialCode, Qty);
                        string sql_ng = string.Format(@"
--保质期
DECLARE @shelfTime NVARCHAR(100)
--条码
DECLARE @finlly_time NVARCHAR(100)
SELECT  @shelfTime = b.ShelfLifeTime ,
        @finlly_time = a.Finally_Time
FROM    dbo.T_Bllb_StockInfo_tbsi AS a
        LEFT JOIN dbo.MdcdatMaterial AS b ON a.MaterialCode = b.MaterialCode
WHERE   a.SerialNumber = '{0}'
IF ( @shelfTime IS NOT NULL
     AND @shelfTime <> '0'
     AND @shelfTime <> ''
   )
    BEGIN
        UPDATE  T_Bllb_StockInfo_tbsi
        SET     Finally_Time = DATEADD(MONTH, CAST(@shelfTime AS INT),
                                       CAST(@finlly_time AS DATETIME))
        WHERE   SerialNumber = '{0}'
    END
", txt_reelid.Text.Trim());
                        Utils.NMS.Exectransql(Utils.uContext, sql_ng, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                        SetLabelMsg(true, "入库成功", "ok");
                        return true;
                    }
                    else
                    {
                        SetLabelMsg(false, "库位错误或库位不属于隔离区", "location");
                        return false;
                    }
                }
            }
        }

        private void SetLabelMsg(bool showflag, string showMsg, string controlname)
        {
            if (showflag)
            {
                lab_msg.ForeColor = Color.DarkGreen;
            }
            else
            {
                lab_msg.ForeColor = Color.Red;
            }
            lab_msg.Text = showMsg;
            if (controlname.Contains("reelid"))
            {
                txt_reelid.SelectAll();
                txt_reelid.Focus();
            }
            else if (controlname.Contains("location"))
            {
                txtLocation.SelectAll();
                txtLocation.Focus();
            }
            else if (controlname.Contains("ok"))
            {
                txt_reelid.Text = string.Empty;
                txtLocation.Text = string.Empty;
                txt_reelid.Focus();
            }
        }

        private void WriteLog(string reelid, string operationType, string materialcode, int qty)
        {
            string sqlcmd = string.Format(@"
INSERT INTO dbo.T_Bllb_MaterialLog_tbml
        ( SerialNumber ,
          CreateTime ,
          OperateType ,
          MaterialCode ,
          QTY ,
          Creator ,
          TBML_ID 
        )
VALUES  ( '{0}' , -- SerialNumber - nvarchar(200)
          GETDATE() , -- CreateTime - datetime
          '{1}' , -- OperateType - nvarchar(50)
          '{2}' , -- MaterialCode - nvarchar(50)
          '{3}', -- QTY - int
          '{4}' , -- Creator - nvarchar(50)
          '{5}' )", reelid, operationType, materialcode, qty, Utils.uContext.UserIDk__BackingField, Guid.NewGuid().ToString());
            Utils.NMS.Exectransql(Utils.uContext, sqlcmd, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
        }

        private void txtLocation_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!ValidateInput())
                {
                    return;
                }
            }
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (string.IsNullOrEmpty(txt_reelid.Text.Trim()))
                {
                    SetLabelMsg(false, "Reelid不能为空", "reelid");
                    return;
                }
                else
                {
                    string sql = string.Format(@"SELECT *  FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber='{0}'", txt_reelid.Text.Trim());
                    DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt.Rows.Count > 0)
                    {
                        SetLabelMsg(false, "Reelid请勿重复入库", "reelid");
                        return;
                    }
                    txtLocation.Focus();
                }
            }
        }
    }
}